<script setup lang="ts">
import {type MachineGroupDTO, MachineGroupPageQry, type PageDTO} from "@/types";
import api from "@/api";
import {onMounted, reactive, ref} from "vue";
import MachineGroupSave from "./MachineGroupSave.vue";
import {useDelete} from "@/hooks";

const machineGroupSaveRef = ref<InstanceType<typeof MachineGroupSave>>();

interface State {
  loading: boolean;
  qry: MachineGroupPageQry;
  result: PageDTO<MachineGroupDTO>;
}

const state = reactive<State>({
  loading: false,
  qry: new MachineGroupPageQry(),
  result: {
    current: 1,
    data: [],
    size: 10,
    totalPage: 1,
    totalSize: 0
  }
});

const loadData = () => {
  state.loading = true;
  api.machineGroup
      .getMachineGroupList(state.qry)
      .then((res) => {
        state.result = res.data;
      })
      .finally(() => {
        state.loading = false;
      });
};

const handlePageSizeChange = () => {
  state.qry.current = 1;
  loadData();
};

const handleDelete = (id: string) => {
  useDelete(() => api.machineGroup.deleteMachineGroup(id)).then(loadData);
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div p-2>
    <el-button type="primary" @click="machineGroupSaveRef?.openDialog()">新建</el-button>
  </div>
  <el-table flex-1 :data="state.result.data" style="width: 100%" v-loading="state.loading"
            border
            stripe
            resizable>
    <el-table-column type="index" width="50" label="#"></el-table-column>
    <el-table-column prop="name" label="名称"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="machineGroupSaveRef?.openDialog(scope.row.id)">
          编辑
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      size="small"
      background
      layout="total, prev, pager, next, sizes, jumper"
      :total="state.result.totalSize"
      v-model:page-size="state.qry.size"
      v-model:current-page="state.qry.current"
      @update:current-page="loadData"
      @update:page-size="handlePageSizeChange"
      p-5
  />
  <machine-group-save ref="machineGroupSaveRef" @success="loadData"/>
</template>
<style scoped lang="scss"></style>
